package com.atguigu.yygh.cmn.controller;

import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.common.model.cmn.Dict;
import com.atguigu.yygh.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Api(tags = "数据字典接口")
@RestController
@RequestMapping("/admin/cmn/dict")
//@CrossOrigin
public class DictController {

    @Autowired
    private DictService dictService;


    /**
     * 根据dictCode获取下级节点
     * @param dictCode 省份编码
     * @return
     */
    @ApiOperation(value = "根据dictCode获取下级节点")
    @GetMapping(value = "/findByDictCode/{dictCode}")
    public Result<List<Dict>> findByDictCode(@PathVariable String dictCode){
       List<Dict> list =  dictService.findByDictCode(dictCode);
       return Result.ok(list);
    }

    /**
     * 根据dictCode和value查询数据字典值
     * @param dictCode
     * @param value
     * @return
     */
    @GetMapping("/getName/{dictCode}/{value}")
    public String getName(@PathVariable String dictCode,
                              @PathVariable String value){
        return dictService.getName(dictCode,value);
    }

    /**
     * 根据value查询数据字典名称
     * @param value
     * @return
     */
    @GetMapping("/getName/{value}")
    public String getName(@PathVariable String value){
        return dictService.getName("", value);
    }

    /**
     *  根据上级id获取子节点数据列表
     */
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @GetMapping("findChildData/{id}")
    @ApiOperation(value = "根据上级id查询子数据列表")
    public Result<List<Dict>> findChildData(@PathVariable Long id){
       List<Dict> dictList =  dictService.findChildData(id);
       return Result.ok(dictList);
    }

    /**
     * 导入数据字典接口
     *  allEntries = true: 方法调用后清空所有缓存
     */
    @CacheEvict(value = "dict", allEntries=true)
    @ApiOperation(value = "数据字典导入")
    @PostMapping("importData")
    public Result<Void> importData(MultipartFile file){
        dictService.importData(file);
        return Result.ok();
    }

    /**
     * 导出数据字典接口
     * @param response
     */
    @ApiOperation(value = "数据字典导出")
    @GetMapping("exportData")
    public void exportData(HttpServletResponse response){
       dictService.exportData(response);
    }

}
